#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System.Xml;
using System;

namespace CchenSoft.Workflow.Loader
{
    public class PermissionDescriptor : AbstractDescriptor
    {
        //~ Instance fields ////////////////////////////////////////////////////////

        protected RestrictionDescriptor restriction;
        protected string name;

        //~ Constructors ///////////////////////////////////////////////////////////

        /**
         * @deprecated use {@link DescriptorFactory} instead
         */
        public PermissionDescriptor()
        {
        }

        /**
         * @deprecated use {@link DescriptorFactory} instead
         */
        public PermissionDescriptor(XmlElement permission)
        {
            Init(permission);
        }

        //~ Methods ////////////////////////////////////////////////////////////////

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public RestrictionDescriptor Restriction
        {
            get { return restriction; }
            set { restriction = value; }
        }

        public override void WriteXML(XmlTextWriter writer, int indent)
        {
            XMLUtil.printIndent(writer, indent++);
            writer.WriteStartElement("permission");

            if (HasId())
            {
                writer.WriteAttributeString("id", Id.ToString());
            }

            writer.WriteAttributeString("name", name);

            restriction.WriteXML(writer, indent);
            XMLUtil.printIndent(writer, --indent);
            writer.WriteEndElement(); // ("</permission>");
        }

        protected void Init(XmlElement permission)
        {
            name = XMLUtil.GetAttributeValue(permission, "name");

            try
            {
                Id = (Convert.ToInt32(XMLUtil.GetAttributeValue(permission, "id")));
            }
            catch (FormatException e)
            {
            }

            restriction = new RestrictionDescriptor((XmlElement)permission.SelectSingleNode("restrict-to"));
        }
    }
}
